# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import traceback
from django.http import JsonResponse
from django.shortcuts import render

from apps.archive_cabinets.models import Cabinet, Lattice, Box
from apps.common.errorcode import response_error, operate_error, Errorquery
from apps.organize_manager.models import CloudAuthUser
from service import create_cabinet, update_cabinet

from inquire import get_cabinets_list, get_cabinet_detail, get_lattices_list, get_box_detail, \
    get_boxes_list
from apps.common.requests import *


# Create your views here.
def add_cabinet(request):
    """新增档案柜"""
    ret = dict(errCode=0, errMsg=operate_error[0])
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        cabinet_params = get_params(body, {"code": "code", "latticesNum": "cabinatNum"},
                                    {"admin": "admin", "material": "material", "storage_location": "posation",
                                     "remark": "remarks"})
        if isinstance(cabinet_params, JsonResponse):
            return cabinet_params
        
        result = create_cabinet(cabinet_params)
        if isinstance(result, Errorquery):
            return err_requests("500")
        return success_requests(result)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500", str(e))


def add_cabinet_box(request):
    ret = dict(errCode=0, errMsg=operate_error[0])
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        cabinet_params = get_params(body, {"code": "code"}, {"specifications": "specifications","lattice": "lattice"})
        if isinstance(cabinet_params, JsonResponse):
            return cabinet_params
        cabinet_params["lattice"] = Lattice.objects.get(id=cabinet_params["lattice"])
        box = Box.objects.create(**cabinet_params)
        return success_requests()
    except Exception as e:
        traceback.print_exc()
        ret['errCode'] = 20001
        ret['errMsg'] = operate_error[20001] + ': ' + str(e)
    return JsonResponse(ret)


def inquire_cabinets_update(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        
        cabinet_params = get_params(body, {"id": "id", "code": "code", "latticesNum": "cabinatNum"},
                                    {"admin": "admin", "material": "material", "storage_location": "posation",
                                     "remark": "remarks"})
        if isinstance(cabinet_params, JsonResponse):
            return cabinet_params
        
        result = update_cabinet(cabinet_params)
        if isinstance(result, Errorquery):
            return err_requests("500")
        return success_requests(result)
    except Exception as e:
        return err_requests("500")


def inquire_cabinets_list(request):
    try:
        res = {}
        cabinets = get_cabinets_list()
        if isinstance(res, Errorquery):
            return err_requests("500")
        res["allAdmin"] = list(CloudAuthUser.objects.all().values("id", "realname"))
        res["allCabinets"] = cabinets
        return success_requests(res)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500")


def inquire_cabinet_detail(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        cabinet_params = get_params(body, {"id": "id"})
        if isinstance(cabinet_params, JsonResponse):
            return cabinet_params
        res = get_cabinet_detail(code=cabinet_params.get("id"))
        if isinstance(res, Errorquery):
            return err_requests("500")
        object = {}
        object["id"] = res.id
        object["material"] = res.material
        object["posation"] = res.storage_location
        object["remarks"] = res.remark
        object["admin"] = res.admin.id
        object["code"] = res.code
        object["cabinatNum"] = Lattice.objects.filter(cabinet=res.id).count()
        return success_requests(object)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500", str(e))


def inquire_lattices_list(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        cabinet_params = get_params(body, {"id": "id"})
        if isinstance(cabinet_params, JsonResponse):
            return cabinet_params
        res = get_lattices_list(cabinet=cabinet_params.get("id"))
        if isinstance(res, Errorquery):
            return err_requests("500", res.msg)
        return success_requests(res)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500", str(e))


def inquire_box_detail(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        box_params = get_params(body, {"id": "id"})
        if isinstance(box_params, JsonResponse):
            return box_params
        boxes = Box.objects.filter(id=box_params.get("id"))
        object = {}
        for box in boxes:
            object["id"] = box.id
            object["code"] = box.code
            object["specifications"] = box.specifications
            object["remark"] = box.remark
            object["lattice"] = box.lattice.id
            return success_requests(object)
        return err_requests("500")
    except Exception as e:
        traceback.print_exc()
        return err_requests("500", str(e))


def inquire_box_update(request):
    try:
        body = get_body(request)
        if isinstance(body, JsonResponse):
            return body
        box_params = get_params(body, {"id": "id", "code": "code"},
                                {"remark": "remark", "specifications": "specifications"})
        if isinstance(box_params, JsonResponse):
            return box_params
        boxes = Box.objects.filter(id=box_params.get("id")).update(**box_params)
        return success_requests(boxes)
    except Exception as e:
        traceback.print_exc()
        return err_requests("500", str(e))


def inquire_boxes_list(request):
    ret = dict(errCode=0, errMsg=operate_error[0])
    try:
        if request.method == 'POST':
            params = request.POST
            lattice = params.get('lattice')
            print 'code: %s' % lattice
            if not lattice:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] + ': 格挡编号不能为空'
                return JsonResponse(ret)
            res = get_boxes_list(lattice=lattice)
            ret["res"] = res
    except Exception as e:
        traceback.print_exc()
        ret['errCode'] = 20001
        ret['errMsg'] = operate_error[20001] + ': ' + str(e)
    return JsonResponse(ret)


def index(request):
    try:
        return render(request, template_name="archive_cabinets/fileCabinet.html")
    except Exception as e:
        print e
        return err_requests("500")
